<template>
  <div class="page-container">
    <div class="handoff">
      <div
        :class="{ selected: item.value == tagVal }"
        :key="item.value"
        v-for="item in tagList"
        @click="tagHandle(item)"
      >
        {{ item.label }}
      </div>
    </div>
    <div class="common-content-wrap" v-show="tagVal == 1">
      <TrTable
        ref="trTable"
        isNeedSelection
        v-model="temSearchParams"
        :searchShowList="temSearchShowList"
        :searchHideList="temSearchHideList"
        :tableColumn="temTableColumn"
        :btnList="temBtnList"
        :tableData="temTableData"
        :total="temTotalNum"
        @temAdd="operationHandle($event, 'temAdd')"
        @enabled="operationHandle($event, 'enabled')"
        @unEnabled="operationHandle($event, 'unEnabled')"
        @temExport="operationHandle($event, 'temExport')"
        @temRowEdit="operationHandle($event, 'temRowEdit')"
        @temRowDelete="operationHandle($event, 'temRowDelete')"
        requestName="getTemListHandle"
      />
    </div>
    <div class="common-content-wrap" v-show="tagVal == 2">
      <TrTable
        ref="materialTable"
        v-model="materialSearchParams"
        :searchShowList="materialSearchShowList"
        :searchHideList="materialSearchHideList"
        :tableColumn="materialTableColumn"
        :btnList="materialBtnList"
        :tableData="materialTableData"
        :total="materialTotalNum"
        :key="keys"
        @materialAdd="operationHandle($event, 'materialAdd')"
        @materialExport="operationHandle($event, 'materialExport')"
        @materialRowEdit="operationHandle($event, 'materialRowEdit')"
        @materialRowDelete="operationHandle($event, 'materialRowDelete')"
        requestName="getMaterialListHandle"
      />
    </div>
    <!-- 模板标签 -->
    <TrForm
      v-model="isShowTemForm"
      :title="checkTemTitle"
      :valueObj.sync="temFormData"
      :formData="temFormObj"
      :list="temFormList"
      :relationList="temRelationList"
      :width="480"
      @close="isShowTemForm = false"
      @confrim="comfrimTemHandle"
    />
    <!-- 标签模板与物料 -->
    <TrForm
      v-model="isShowMaterialForm"
      :title="checkMaterialTitle"
      :valueObj.sync="materialFormData"
      :formData="materialFormObj"
      :list="materialFormList"
      :relationList="materialRelationList"
      :width="480"
      @close="isShowMaterialForm = false"
      @confrim="comfrimMaterialHandle"
    />
  </div>
</template>
<script>
import {
  getTemList,
  temAdd,
  temUpdate,
  temEdit,
  temRemove,
  getMaterialList,
  materialAdd,
  materialEdit,
  materialDelete,
} from "@/api/baseCode/labelTemplate";
import { getColor } from "@/utils/billColor";
import enumData from "@/utils/enumCode.js";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrForm from "@/components/Tr-form/Tr-form-popup.vue";
import { cloneDeep } from "lodash-es";
export default {
  name: "LabelTemplateBox",
  components: {
    TrTable,
    TrForm,
  },
  data: () => ({
    keys: 1,
    tagList: [
      { label: "标签模板", value: 1 },
      { label: "标签模板与物料", value: 2 },
    ],
    tagVal: 1,
    temSearchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    temSearchHideList: [
      {
        id: "tempCode",
        label: "标签模板编码",
        type: "input",
        width: 33.3,
        value: "",
      },
      {
        id: "tempName",
        label: "标签模板名称",
        type: "input",
        width: 33.3,
        value: "",
      },
      {
        id: "tempTypeList",
        label: "模板类型",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
      {
        id: "stateList",
        label: "状态",
        type: "multiSelect",
        width: 33.3,
        value: [],
        list: [],
      },
    ],
    temSearchParams: {
      current: 1,
      size: 10,
    },
    temTableColumn: [
      {
        type: "text",
        label: "标签模板编码",
        value: "tempCode",
        width: 200,
      },
      {
        type: "text",
        label: "状态",
        value: "stateName",
      },
      {
        type: "text",
        label: "模板类型",
        value: "tempTypeName",
      },
      {
        type: "text",
        label: "标签模板名称",
        value: "tempName",
      },
      {
        type: "image",
        label: "标签样式图片",
        value: "pictureList",
      },
      {
        type: "text",
        label: "模板描述",
        value: "remark",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "编辑",
            option: "temRowEdit",
          },
          {
            label: "删除",
            option: "temRowDelete",
          },
        ],
      },
    ],
    temBtnList: [
      {
        label: "新增",
        option: "temAdd",
        color: "blue",
      },
      {
        label: "启用",
        option: "enabled",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "停用",
        option: "unEnabled",
        color: "white",
        isRelaTable: true,
      },
      {
        label: "导出",
        option: "temExport",
        color: "white",
      },
    ],
    temTotalNum: 0,
    temTableData: [],
    isShowTemForm: false,
    temFormData: {},
    temFormObj: {},
    temFormList: [
      {
        label: "标签模板编码",
        type: "input",
        width: 100,
        value: "",
        placeholder: "系统自动生成",
        id: "tempCode",
        isNeed: false,
        disabled: true,
      },
      {
        label: "模板类型",
        type: "select",
        width: 100,
        value: "",
        list: [],
        id: "tempType",
      },
      {
        label: "标签模板名称",
        type: "input",
        width: 100,
        value: "",
        id: "tempName",
      },
      {
        label: "是否启用",
        type: "radio",
        width: 100,
        value: 1,
        list: [
          {
            label: "是",
            value: 1,
          },
          {
            label: "否",
            value: 0,
          },
        ],
        id: "state",
      },
      {
        label: "样式图片",
        type: "select",
        width: 100,
        value: "",
        list: [],
        id: "fileId",
      },
      {
        label: "图片预览",
        type: "image",
        width: 100,
        value: "",
        id: "preview",
        reviewValue: "pictureList",
        isNeed: false,
      },
      {
        isNeed: false,
        id: "remark",
        label: "模板描述",
        type: "textarea",
        width: 100,
        value: "",
      },
    ],
    temRelationList: [
      {
        id: "fileId",
        relaList: [
          {
            relaId: "preview",
            relaValue: "remark",
            disabled: true,
          },
        ],
      },
    ],
    materialSearchShowList: [
      {
        isNeed: true,
        startStr: "createTimeStart",
        endStr: "createTimeEnd",
        id: "createTime",
        type: "daterange",
        width: 80,
        label: "创建时间",
        value: [],
        radio: 1,
        timePeriod: true,
      },
    ],
    materialSearchHideList: [
      {
        id: "materialCategoryId",
        label: "物料类别",
        type: "loadselect",
        width: 33.3,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material-category/page",
          method: "post",
          searchKey: "categoryName",
          rlLabel: "categoryName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        value: "",
      },
      {
        id: "materialId",
        label: "物料编码",
        type: "loadselect",
        width: 33.3,
        selectedLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        value: "",
      },
    ],
    materialSearchParams: {
      current: 1,
      size: 10,
    },
    materialTableColumn: [
      {
        type: "text",
        label: "标签模板编码",
        value: "tempCode",
        width: 200,
      },
      {
        type: "text",
        label: "模板类型",
        value: "tempTypeName",
      },
      {
        type: "text",
        label: "标签模板名称",
        value: "tempName",
      },
      {
        type: "image",
        label: "标签样式图片",
        value: "pictureList",
      },
      {
        type: "text",
        label: "物料类别",
        value: "materialCategoryName",
      },
      {
        type: "text",
        label: "物料编码",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "text",
        label: "物料规格",
        value: "materialSpec",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },

      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "编辑",
            option: "materialRowEdit",
          },
          {
            label: "删除",
            option: "materialRowDelete",
          },
        ],
      },
    ],
    materialBtnList: [
      {
        label: "新增",
        option: "materialAdd",
        color: "blue",
      },
      {
        label: "导出",
        option: "materialExport",
        color: "white",
      },
    ],
    materialTotalNum: 0,
    materialTableData: [],
    isShowMaterialForm: false,
    materialFormData: {},
    materialFormObj: {},
    materialFormList: [
      {
        id: "tempId",
        label: "标签模板名称",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        reviewLabel: "tempName",
        requestObj: {
          url: "/api/mes-production-service/label-temp/page",
          method: "post",
          searchKey: "tempName",
          rlLabel: "tempName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          stateList: [1],
        },
        value: "",
      },
      {
        label: "模板类型",
        type: "input",
        width: 100,
        value: "",
        id: "tempTypeName",
        placeholder: "系统带出",
        isNeed: false,
      },
      {
        label: "标签模板编码",
        type: "input",
        width: 100,
        value: "",
        id: "tempCode",
        placeholder: "系统带出",
        isNeed: false,
      },
      {
        label: "样式图片",
        type: "image",
        width: 100,
        value: "",
        id: "pictureList",
        isNeed: false,
      },
      {
        id: "materialCategoryId",
        label: "物料类别",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        reviewLabel: "materialCategoryName",
        requestObj: {
          url: "/api/mes-production-service/material-category/page",
          method: "post",
          searchKey: "categoryName",
          rlLabel: "categoryName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
        value: "",
      },
      {
        id: "materialId",
        label: "物料编码",
        type: "loadselect",
        width: 100,
        selectedLabel: "",
        reviewLabel: "materialCode",
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
        value: "",
        isNeed: false,
      },
      {
        label: "物料名称",
        id: "materialName",
        type: "input",
        width: 100,
        value: "",
        placeholder: "系统带出",
        isNeed: false,
        disabled: true,
      },
    ],
    materialRelationList: [
      {
        id: "tempId",
        relaList: [
          {
            relaId: "tempTypeName",
            relaValue: "tempTypeName",
            disabled: true,
          },
          {
            relaId: "tempCode",
            relaValue: "tempCode",
            disabled: true,
          },
          {
            relaId: "pictureList",
            relaValue: "pictureList",
            disabled: true,
          },
        ],
      },
      {
        id: "materialCategoryId",
        relaList: [
          {
            relaId: "materialId",
            disabled: false,
            params: [
              {
                labelWord: "materialCategoryId",
                realWord: "rlValue",
                editWord: "materialCategoryId",
              },
            ],
          },
        ],
      },
      {
        id: "materialId",
        relaList: [
          {
            relaId: "materialName",
            relaValue: "materialName",
            disabled: true,
          },
          {
            relaId: "materialCategoryId",
            disabled: false,
            isNotStrict: true,
            params: [
              {
                labelWord: "materialCategoryId",
                realWord: "materialCategoryId",
                editWord: "materialCategoryId",
              },
            ],
          },
        ],
      },
    ],
  }),
  computed: {
    ids() {
      return this.$refs.trTable.selectionList.map((item) => item.id);
    },
    checkTemTitle() {
      return this.temFormObj.id ? "编辑" : "新增";
    },
    checkMaterialTitle() {
      return this.materialFormObj.id ? "编辑" : "新增";
    },
  },
  methods: {
    materialRemoveHandle(idList) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          const { data: res } = await materialDelete(idList);
          if (res.code != 200) return;
          this.resetHandle(2);
        })
        .catch(() => {});
    },
    async comfrimMaterialHandle() {
      if (this.materialFormObj.id) {
        this.materialFormData.id = this.materialFormObj.id;
        const { data: res } = await materialEdit(this.materialFormData);
        if (res.code != 200) return;
      } else {
        const { data: res } = await materialAdd(this.materialFormData);
        if (res.code != 200) return;
      }
      this.resetHandle(2);
    },
    async getMaterialListHandle() {
      const { data: res } = await getMaterialList(this.materialSearchParams);
      if (res.code != 200) return this.$message.error(res.msg);
      this.$validateData(res.data.records);
      this.materialTableData = res.data.records;

      this.materialTableData.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
        item.fileId = item.fileIdList[0];
        // this.$forceUpdate();
      });
      this.materialTotalNum = res.data.total;
    },
    temRemoveHandle(idList) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          const { data: res } = await temRemove(idList);
          if (res.code != 200) return;
          this.resetHandle();
        })
        .catch(() => {});
    },
    updateStateHandle(params) {
      let tip =
        params.state == 1
          ? this.$t("tip.enableTip")
          : this.$t("tip.unenableTip");
      this.$textShow({
        title: this.$t("tip.label"),
        content: [tip],
      })
        .then(async () => {
          const { data: res } = await temUpdate(params);
          if (res.code != 200) return;
          this.resetHandle();
        })
        .catch(() => {});
    },
    resetHandle(type) {
      this.$message.success(this.$t("msg.success"));

      if (type == 2) {
        this.isShowMaterialForm = false;
        this.materialFormObj = {};
        this.getMaterialListHandle();
      } else {
        this.isShowTemForm = false;
        this.temFormObj = {};
        this.getTemListHandle();
        this.$refs.trTable.clearSelect();
      }
    },
    async comfrimTemHandle() {
      if (this.temFormObj.id) {
        this.temFormData.id = this.temFormObj.id;
        const { data: res } = await temEdit(this.temFormData);
        if (res.code != 200) return;
      } else {
        const { data: res } = await temAdd(this.temFormData);
        if (res.code != 200) return;
      }
      this.resetHandle();
    },
    async getTemListHandle() {
      const { data: res } = await getTemList(this.temSearchParams);
      if (res.code != 200) return this.$message.error(res.msg);
      this.$validateData(res.data.records);
      this.temTableData = res.data.records;

      this.temTableData.forEach((item) => {
        item["stateNameColor"] = getColor("QT", item.state);
        item.fileId = item.fileIdList[0];
      });

      this.temTotalNum = res.data.total;
    },
    tagHandle(tagObj) {
      if (tagObj.value == this.tagVal) return;
      this.tagVal = tagObj.value;
      if (tagObj.value == 2) {
        this.$refs.materialTable.updateKey();
      } else {
        this.$refs.trTable.updateKey();
      }
    },
    operationHandle(val, type) {
      this.$validateData(val, 3);
      switch (type) {
        case "temAdd":
          this.temFormObj = {};
          this.isShowTemForm = true;
          break;
        case "enabled":
          this.updateStateHandle({
            idList: this.ids,
            state: 1,
          });
          break;
        case "unEnabled":
          this.updateStateHandle({
            idList: this.ids,
            state: 0,
          });
          break;
        case "temRowEdit":
          this.temFormObj = val;
          this.isShowTemForm = true;
          break;
        case "temRowDelete":
          this.temRemoveHandle([val.id]);
          break;
        case "temExport":
          this.$exportHandle({
            vm: this,
            params: this.temSearchParams,
            code: 1,
          });
          break;
        case "materialAdd":
          this.materialFormObj = {};
          this.isShowMaterialForm = true;
          break;
        case "materialRowEdit":
          this.materialFormObj = val;
          this.isShowMaterialForm = true;
          break;
        case "materialRowDelete":
          this.materialRemoveHandle([val.id]);
          break;
        case "materialExport":
          this.$exportHandle({
            vm: this,
            params: this.materialSearchParams,
            code: 2,
          });
          break;

        default:
          break;
      }
    },
    async getAllOptions() {
      const typeRes = await this.$fetchEnumData(
        [enumData.labelTempType, enumData.labelTemp, enumData.isEnabledList],
        false
      );
      let typeItem = this.$findByProperty(this.temFormList, "id", "tempType");
      let typeCol = this.$findByProperty(
        this.temSearchHideList,
        "id",
        "tempTypeList"
      );
      this.$set(typeItem, "list", typeRes[enumData.labelTempType]);
      this.$set(typeCol, "list", typeRes[enumData.labelTempType]);
      let temItem = this.$findByProperty(this.temFormList, "id", "fileId");
      this.$set(temItem, "list", typeRes[enumData.labelTemp]);
      let enabledItem = this.$findByProperty(
        this.temSearchHideList,
        "id",
        "stateList"
      );
      this.$set(enabledItem, "list", typeRes[enumData.isEnabledList]);
      this.materialSearchHideList = [
        ...cloneDeep(
          this.temSearchHideList.slice(0, this.temSearchHideList.length - 1)
        ),
        ...this.materialSearchHideList,
      ];
    },
  },
  created() {
    this.getAllOptions();
  },
};
</script>
